package com.skp.shaphan.report;

import java.io.IOException;

import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.exceptions.COSVisitorException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDMatrix;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.edit.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;

public class BaseReport {
	private PDDocument doc;
	private PDPage currentPage;
	private float x;
	private float y;
	private PDPageContentStream s;
	private float margin = 30f;
	private int normalFontSize = 12;

	public BaseReport() throws IOException {
		initDoc();
	}
	
	private void initDoc() throws IOException {
		doc = new PDDocument();
		currentPage = new PDPage();
		doc.addPage(currentPage);
		s = new PDPageContentStream(doc, currentPage);
	}
	
	public void writeTitle(String title) throws IOException {
		// setup the font
		PDFont font = PDType1Font.HELVETICA_BOLD;
		int fontSize = 25;

		// get position:
		PDRectangle mb = currentPage.getMediaBox();
		float height = font.getFontBoundingBox().getHeight() / 1000f * fontSize; 
		float y = mb.getHeight() - margin - height;
		float width = font.getStringWidth(title);
		
		s.beginText();
		s.setFont(font, fontSize);
		s.moveTextPositionByAmount(margin, y);
		s.drawString(title);
		s.endText();
		
		y -= height * 0.05f;
		s.drawLine(margin, y, width - margin, y);
		
		this.y = y;
	}
	
	public void writeString(String text) throws IOException {
		// setup the font
		PDFont font = PDType1Font.HELVETICA;
		int fontSize = normalFontSize;

		// get position:
		float height = font.getFontBoundingBox().getHeight() / 1000f * fontSize * 1.05f;
		y -= height;
		
		s.beginText();
		s.setFont(font, fontSize);
		s.moveTextPositionByAmount(margin, y);
		s.drawString(text);
		s.endText();
	}
	
	public void save(String path) throws COSVisitorException, IOException {
		s.close();
		doc.save(path);
	}
	
	public void close() throws IOException {
		doc.close();
	}

	public int getNormalFontSize() {
		return normalFontSize;
	}

	public void setNormalFontSize(int normalFontSize) {
		this.normalFontSize = normalFontSize;
	}	
}
